import type { FC } from 'react';
import style from './index.less';
import React, { Fragment, useState, useEffect } from 'react';
import { Avatar, Button, Form, Input, message, Modal, Tag, Upload } from 'antd';
import { EditOutlined, LoadingOutlined, PlusOutlined, UserOutlined } from '@ant-design/icons';
import { updateAvatar, currentUser } from './service';
import moment from 'moment';
import IconFont from '@/components/Icon';

interface Props {}
const Header: FC<Props> = () => {
  const [visible, setVisible] = useState(false);
  const [userInfo, setUserInfo] = useState();
  const userId = localStorage.getItem('user_id');
  const color = ['green', 'cyan', 'blue', 'geekblue', 'purple'];
  // 输入框是否显示
  const [inputStatu, setInputStatu] = useState(false);
  const handleOk = () => {
    updateAvatar({ user_id: userId, user_img: imageUrl }).then(res => {
      console.log(res);
    });
    setVisible(false);
    setImageUrl('');
  };

  const handleCancel = () => {
    setVisible(false);
    setImageUrl('');
  };
  // 图片地址
  const [imageUrl, setImageUrl] = useState<string>();
  // 加载
  const [loading, setLoading] = useState(false);
  // 上传前
  const beforeUpload = file => {
    // 图片格式
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };
  // 转为base64
  const getBase64 = (img: Blob, callback: any) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };
  // 上传图片
  const handleChange = (info: any) => {
    console.log(info.file, 'info');
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      getBase64(info.file.originFileObj, (imageUrl: any) => {
        setImageUrl(info.file.response.url);
        setLoading(false);
      });
    }
  };
  const onFinish = () => {
    alert(1);
  };
  const getUserInfo = () => {
    currentUser({ user_id: localStorage.getItem('user_id') }).then(res => {
      setUserInfo({ ...res.data });
    });
  };
  useEffect(() => {
    getUserInfo();
  }, []);
  return (
    <div className={style.container}>
      <div className={style.ava_con}>
        <Avatar src={userInfo?.user_img} className={style.large} />
        <div
          className={style.cover}
          onClick={() => {
            setVisible(true);
          }}
        />
        <Modal title="上传头像" visible={visible} onOk={handleOk} onCancel={handleCancel}>
          {/* 这么写的classname的样式加不上 */}
          <div className="upload" style={{ display: 'flex' }}>
            <Upload
              // 对应后端的 ctx.request.files.file
              name="file"
              listType="picture-card"
              className="avatar-uploader"
              showUploadList={false}
              action="/api/client/Upload"
              beforeUpload={beforeUpload}
              onChange={handleChange}
              style={{ width: '100px', height: '120px', marginTop: '20px' }}
            >
              {imageUrl ? (
                <img src={imageUrl} alt="avatar" style={{ width: '100%', marginTop: '10px' }} />
              ) : (
                <div>
                  {loading ? <LoadingOutlined /> : <PlusOutlined />}
                  <div style={{ marginTop: 8 }}>Upload</div>
                </div>
              )}
            </Upload>
            <Avatar
              src={imageUrl}
              style={{ width: '120px', height: '120px', lineHeight: '120px' }}
            />
          </div>
        </Modal>
      </div>
      <div className={style.info}>
        <div>
          {inputStatu ? (
            <div style={{ display: 'flex', marginBottom: '10px', height: '30px' }}>
              <Form
                name="basic"
                // labelCol={{ span: 8 }}
                // wrapperCol={{ span: 16 }}
                initialValues={userInfo}
                onFinish={onFinish}
                // onFinishFailed={onFinishFailed}
                autoComplete="off"
                style={{ display: 'flex', width: '100%' }}
              >
                <Form.Item
                  name="username"
                  rules={[{ required: true, message: 'Please input your username!' }]}
                  style={{ height: '40px', width: '300px' }}
                >
                  <Input prefix={<UserOutlined className="site-form-item-icon" />} width={300} />
                </Form.Item>
              </Form>
              <Button type="primary" htmlType="submit" style={{ marginLeft: '10px' }} shape="round">
                确定
              </Button>
              <Button
                style={{ marginLeft: '10px' }}
                onClick={() => {
                  setInputStatu(false);
                }}
                shape="round"
              >
                取消
              </Button>
            </div>
          ) : (
            <h3 style={{ fontWeight: '700' }} className={style.username}>
              {userInfo?.username}{' '}
              <EditOutlined
                onClick={() => {
                  setInputStatu(true);
                }}
              />
            </h3>
          )}
          <div className={style.date}>
            <IconFont type="icondaima" className={style.icon} />
            <div className={style.date_text}>
              码龄：
              {moment(userInfo?.createdAt, 'YYYY-MM-DD HH:mm:ss').fromNow().replace('前', ' ')}
            </div>
            <div style={{ marginLeft: '40px' }}>
              {userInfo?.tag?.split(',').map((item, index) => (
                <Tag color={color[index]}>{item}</Tag>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Header;
